<template>
  <n-drawer v-model:show="isDrawer" width="600" :auto-focus="false" @after-leave="handleReset">
    <n-drawer-content title="商品管理" closable>
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="top"
        :label-width="100"
      >
        <n-form-item label="名称" path="name">
          <n-input
            placeholder="请输入名称"
            v-model:value="formParams.name"
          />
        </n-form-item>
        <n-form-item label="售价" path="danjia">
          <n-input placeholder="请输入售价" v-model:value="formParams.danjia" />
        </n-form-item>
        <n-form-item label="成本价" path="costprice">
          <n-input placeholder="请输入成本价" v-model:value="formParams.costprice" />
        </n-form-item>
        <n-form-item label="仓位" path="positions">
          <n-radio-group v-model:value="formParams.positions" name="positions">
              <n-space>
                <n-radio :key="1" :value="1">左仓</n-radio>
                <n-radio :key="2" :value="2">右仓</n-radio>
              </n-space>
            </n-radio-group>
        </n-form-item>
        <n-form-item label="图片" path="sitepicture">
          <BasicUpload
              :action="`${uploadUrl1}/api/common/cosupdate`"
              :width="100"
              :height="100"
              name="file"
              @uploadChange="changeSitePicture"
              :max="1"
              :maxSize="10"
              v-model:value="sitepicture"
              helpText="单个文件不超过10MB，最多只能上传1个文件"
          />
        </n-form-item>
      </n-form>
      <template #footer>
        <n-space>
          <n-button @click="handleReset">重置</n-button>
          <n-button type="primary" :loading="subLoading" @click="formSubmit">提交</n-button>
        </n-space>
      </template>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup>
  import {  ref } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { goodsinfo,goodsedit } from '@/api/device/charger';
  import { useGlobSetting } from '@/hooks/setting';
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = uploadUrl;
  const sitepicture = ref([]);

  const rules: FormRules = {
    name: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    }
  };

  const defaultValueRef = () => ({
    id: null,
    name: '',
    danjia: '',
    costprice: '',
    sitepicture: '',
    goodscharger_id: '',
    positions: 1,
  });

  const message = useMessage();
  const formRef: any = ref(null);
  const isDrawer = ref(false);
  const subLoading = ref(false);
  const formParams = ref(defaultValueRef());
  const emit = defineEmits(['change']);

  async function openDrawer(id?) {
    if (id) {
      formParams.value.id = id;
      formParams.value.goodscharger_id = id;
      getInfo();
      return;
    }else{
      sitepicture.value = [];
    }
    isDrawer.value = true;
  }

  function closeDrawer() {
    isDrawer.value = false;
  }

  function formSubmit() {
    formParams.value.sitepicture = sitepicture.value[0];
    formRef.value.validate((errors) => {
      if (!errors) {
        const msg = formParams.value.id ? '编辑成功' : '添加成功';
        if (formParams.value.id) {
          goodsedit(formParams.value).then((_) => {
            message.success(msg);
            emit('change');
            handleReset();
            closeDrawer();
          });
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value.restoreValidation();
    sitepicture.value = [];
    formParams.value = Object.assign(formParams.value, defaultValueRef());
  }

  function getInfo() {
    goodsinfo({ goodscharger_id: formParams.value.id }).then((res) => {
      const params = {
        id: formParams.value.id,
        name: res.name,
        danjia: res.danjia,
        costprice: res.costprice,
        sitepicture: res.sitepicture,
        positions: res.positions,
      };

      sitepicture.value[0] = res.sitepicture;
      
      formParams.value = Object.assign(formParams.value, params);
      isDrawer.value = true;
    });
  }

  function changeSitePicture(file){
    sitepicture.value = file;
  }

  defineExpose({
    openDrawer,
    closeDrawer,
  });
</script>
